// 语言数据结构
const languageData = {
  zh: {
    // 导航栏
    'nav-logo': '自由编导',
    'nav-product': '产品',
    'nav-editor': '模板编辑器',
    'nav-workflow': 'Make自动化',
    'nav-render': '导出与渲染',
    'nav-pricing': '价格',
    'nav-docs': '文档',
    'nav-examples': '示例',
    'nav-login': '登录',
    'nav-register': '注册',
    'badge-points': '送积分',
    
    // Hero区域
    'hero-title': '用"Make+剪映"，批量生成高质量视频',
    'hero-subtitle': '基于剪映 API 的自动化视频合成平台。可视化搭建模板，连接 make.com 的 3000+ 应用，自动替换文字/图片/音频/视频等素材，支持剪映工程导入与在线渲染。',
    'hero-bullet-1': '<strong>可视化编辑：</strong>结构、背景、视频、音频、图片、文字、样式、特效、转场一站式编排。',
    'hero-bullet-2': '<strong>AI自动化：</strong>连接 3000+ 应用与 AI 能力，批量替换素材，自动出片。',
    'hero-bullet-3': '<strong>剪映生态：</strong>生成可导入本地剪映的工程文件，或直接在线渲染。',
    'hero-bullet-4': '<strong>清晰计费：</strong>按模板与时长计费，成本清晰可预测，新用户赠送 120 积分。',
    'hero-cta-start': '立即开始',
    'hero-cta-examples': '查看示例模板',
    'hero-cta-docs': '文档与指南',
    
    // 工作流程
    'workflow-title': '3 步实现自动化视频生产',
    'workflow-step1-title': '可视化搭建模板',
    'workflow-step1-desc': '在自由编导的可视化编辑器中，搭建视频模板：结构、背景、视频、音频、图片、文字，以及相应样式、特效、转场。',
    'workflow-step2-title': '运行Make工作流',
    'workflow-step2-desc': '在 make.com 搜索「自由编导」应用，创建工作流，替换模板中的文字/音频/视频/图片素材，实现批量生成。',
    'workflow-step3-title': '视频导出/渲染',
    'workflow-step3-desc': '生成可直接导入剪映的工程文件进行本地渲染，或选择在线渲染直接导出视频。',
    
    // 编辑器功能
      'editor-title': '可视化模板编辑器：为规模化而生',
      'editor-feature1-title': '多轨结构编排',
      'editor-feature1-desc': '时间线与片段结构管理，支持片段复用与占位符定义',
      'editor-feature2-title': '丰富媒体类型',
      'editor-feature2-desc': '视频/音频/图片/文字/背景统一管理',
      'editor-feature3-title': '样式与特效',
      'editor-feature3-desc': '字体、颜色、阴影、动效、滤镜、转场、关键帧',
      'editor-feature4-title': '参数化占位',
      'editor-feature4-desc': '可在模板中声明变量，供工作流自动替换',
      'editor-feature5-title': '预览与版本',
      'editor-feature5-desc': '所见即所得预览，版本保存与回滚',
      'editor-feature6-title': '工程一致性',
      'editor-feature6-desc': '与剪映工程规范兼容，减少回导差异',
    
    // 自动化工作流
      'automation-title': '连接 make.com 的 2000+ 应用，释放自动化与 AI',
      'automation-desc': '在 make.com 中搜索并使用"自由编导"应用，组合数据源、AI 能力与素材库，实现从数据到成片的自动化生产。',

      // 渲染与输出
      'render-title': '剪映工程导入与在线渲染，双路径出片',
      'render-desc': '两种方式可自由选择，互不冲突。',
      'render-or': 'OR',
      'render-local-title': '本地流程（导出剪映工程）',
      'render-local-desc': '生成可导入剪映的软件草稿工程文件，本地渲染。',
      'render-local-tag1': '可校对',
      'render-local-tag2': '可二次微调',
      'render-local-tag3': '适合本地素材',
      'render-online-title': '在线渲染',
      'render-online-desc': '无需本地环境，云端完成渲染，直接获得成品视频。',
      'render-online-tag1': '免环境',
      'render-online-tag2': '快交付',
      'render-online-tag3': '适合批量任务',

      // 定价
    'pricing-title': '清晰透明的积分计费',
    'pricing-desc': '透明清晰的计费标准，让您的成本可预测',
    'pricing-rules-title': '📋 积分规则说明',
    'pricing-rules-recharge': '充值比例',
    'pricing-rules-recharge-desc': '1 元人民币 = 10 积分',
    'pricing-rules-template': '创建模板',
    'pricing-rules-template-desc': '每个模板 20 积分（一次性）',
    'pricing-rules-generate': '通过 make 生成视频',
    'pricing-rules-generate-desc': '每秒 1 积分',
    'pricing-rules-render': '在线渲染',
    'pricing-rules-render-desc': '每秒 2 积分（可选）',
    'pricing-rules-gift': '新用户赠送',
    'pricing-rules-gift-desc': '注册即送 120 积分',
    'pricing-examples-title': '💡 计费示例',
    'pricing-examples-desc': '看看实际使用场景的积分消耗',
    'pricing-example-a': '示例 A：30 秒视频',
    'pricing-example-a-generate': '生成视频',
    'pricing-example-a-generate-points': '30 积分',
    'pricing-example-a-render': '在线渲染（可选）',
    'pricing-example-a-render-points': '60 积分',
    'pricing-example-a-total': '合计',
    'pricing-example-a-total-points': '90 积分',
    'pricing-example-a-note': '不含模板创建',
    'pricing-example-b': '示例 B：10 个 45 秒视频',
    'pricing-example-b-generate': '生成视频',
    'pricing-example-b-generate-points': '450 积分',
    'pricing-example-b-render': '在线渲染（可选）',
    'pricing-example-b-render-points': '900 积分',
    'pricing-example-b-total': '合计',
    'pricing-example-b-total-points': '1350 积分',
    'pricing-example-b-note': '不含模板创建',
    'pricing-calculator-title': '🧮 积分试算器',
    'pricing-calculator-desc': '快速计算您的项目成本',
    'pricing-calculator-duration': '视频时长（秒）',
    'pricing-calculator-count': '数量（条）',
    'pricing-calculator-render': '是否在线渲染（可选）',
    'pricing-calculator-points': '预计消耗积分',
    'pricing-calculator-rmb': '人民币参考',
    'pricing-calculator-pay': '立即支付',
    
    // 应用场景
    'scenarios-title': '把重复的视频生产，交给自动化',
    'scenario1-title': '电商与品牌',
    'scenario1-desc': '批量商品卡片视频、促销/节日素材、达口播模板化。',
    'scenario1-tag1': '商品展示',
    'scenario1-tag2': '促销活动',
    'scenario2-title': '教育与培训',
    'scenario2-desc': '大纲驱动的知识点视频、题目讲解、术语卡片。',
    'scenario2-tag1': '知识点',
    'scenario2-tag2': '题目讲解',
    'scenario3-title': '媒体与资讯',
    'scenario3-desc': '热点快报、数据榜单、城市/行业周报。',
    'scenario3-tag1': '热点快报',
    'scenario3-tag2': '数据榜单',
    'scenario4-title': '企业内训/公关',
    'scenario4-desc': 'SOP 演示、季度报告、活动回顾。',
    'scenario4-tag1': 'SOP演示',
    'scenario4-tag2': '季度报告',
    
    // 用户评价
    'testimonials-title': '他们正在用自由编导提升视频生产效率',
    'testimonial1-name': '张总监',
    'testimonial1-company': '某电商品牌',
    'testimonial1-quote': '"批量视频生产从天到小时，效率提升显著。"',
    'testimonial2-name': '李经理',
    'testimonial2-company': '教育科技公司',
    'testimonial2-quote': '"模板 + 自动化，让我们的视频风格保持一致。"',
    'testimonial3-name': '王运营',
    'testimonial3-company': '媒体工作室',
    'testimonial3-quote': '"接入剪映工程后，校对与二次编辑非常顺滑。"',
    'testimonial4-name': '陈主管',
    'testimonial4-company': '企业培训部',
    'testimonial4-quote': '"在线渲染适合批量任务，交付更快。"',
    'testimonial5-name': '刘创始人',
    'testimonial5-company': '内容创业团队',
    'testimonial5-quote': '"按时长计费，成本清晰可控。"',
    
    // 最终CTA
    'final-cta-title': '现在开始，打造你的自动化视频生产线',
    'final-cta-start': '立即开始',
    'final-cta-examples': '查看示例模板',
    'final-cta-guide': '查看接入指南',
    
    // Footer
    'footer-product': '产品',
    'footer-features': '特性',
    'footer-pricing': '价格',
    'footer-examples': '示例',
    'footer-resources': '资源',
    'footer-docs': '文档',
    'footer-api': 'API',
    'footer-tutorials': '教程',
    'footer-support': '支持',
    'footer-terms': '服务条款',
    'footer-privacy': '隐私政策',
    'footer-customer-service': '客服支持',
    'footer-qr-text': '扫码联系客服',
    'footer-copyright': '© 超级斜杠 / 自由编导',
    'footer-icp': '皖ICP备2024068632号-6',
    'footer-police': ' 皖公网安备34011102003738号 '
  },
  en: {
    // 导航栏
    'nav-logo': 'FreeDirector',
    'nav-product': 'Product',
    'nav-editor': 'Template Editor',
    'nav-workflow': 'Make Automation',
    'nav-render': 'Export & Render',
    'nav-pricing': 'Pricing',
    'nav-docs': 'Docs',
    'nav-examples': 'Examples',
    'nav-login': 'Login',
    'nav-register': 'Sign Up',
    'badge-points': 'Free Credits',
    
    // Hero区域
    'hero-title': 'Batch Generate High-Quality Videos with "Make+JianYing"',
    'hero-subtitle': 'An automated video synthesis platform based on JianYing API. Visually build templates, connect to 3000+ apps on make.com, automatically replace text/images/audio/video materials, support JianYing project import and online rendering.',
    'hero-bullet-1': '<strong>Visual Editing:</strong> One-stop arrangement of structure, background, video, audio, images, text, styles, effects, and transitions.',
    'hero-bullet-2': '<strong>AI Automation:</strong> Connect 3000+ apps and AI capabilities, batch replace materials, automatic video production.',
    'hero-bullet-3': '<strong>JianYing Ecosystem:</strong> Generate project files that can be imported into local JianYing, or render online directly.',
    'hero-bullet-4': '<strong>Clear Billing:</strong> Billing by template and duration, clear and predictable costs, new users get 120 credits.',
    'hero-cta-start': 'Get Started',
    'hero-cta-examples': 'View Example Templates',
    'hero-cta-docs': 'Documentation & Guide',
    
    // 工作流程
    'workflow-title': '3 Steps to Automated Video Production',
    'workflow-step1-title': 'Visual Template Building',
    'workflow-step1-desc': 'In FreeDirector\'s visual editor, build video templates: structure, background, video, audio, images, text, and corresponding styles, effects, transitions.',
    'workflow-step2-title': 'Run Make Workflow',
    'workflow-step2-desc': 'Search for "FreeDirector" app on make.com, create workflows, replace text/audio/video/image materials in templates for batch generation.',
    'workflow-step3-title': 'Video Export/Render',
    'workflow-step3-desc': 'Generate project files that can be directly imported into JianYing for local rendering, or choose online rendering for direct video export.',
    
    // 编辑器功能
      'editor-title': 'Visual Template Editor: Built for Scale',
      'editor-feature1-title': 'Multi-track Structure',
      'editor-feature1-desc': 'Timeline and segment structure management with reusable clips and placeholders',
      'editor-feature2-title': 'Rich Media Types',
      'editor-feature2-desc': 'Unified management of video/audio/images/text/backgrounds',
      'editor-feature3-title': 'Styles & Effects',
      'editor-feature3-desc': 'Fonts, colors, shadows, animations, filters, transitions, keyframes',
      'editor-feature4-title': 'Parameterized Placeholders',
      'editor-feature4-desc': 'Declare variables in templates for automatic workflow replacement',
      'editor-feature5-title': 'Preview & Versioning',
      'editor-feature5-desc': 'WYSIWYG preview with version saving and rollback',
      'editor-feature6-title': 'Project Consistency',
      'editor-feature6-desc': 'Compatible with JianYing project standards, reducing export differences',
    
    // 自动化工作流
      'automation-title': 'Connect 2000+ Apps on make.com, Unleash Automation & AI',
      'automation-desc': 'Search and use the "Free Director" app in make.com, combine data sources, AI capabilities and material libraries to achieve automated production from data to finished videos.',

      // 渲染与输出
      'render-title': 'JianYing Project Import & Online Rendering, Dual Output Paths',
      'render-desc': 'Two methods to choose freely, no conflict.',
      'render-or': 'OR',
      'render-local-title': 'Local Workflow (Export JianYing Project)',
      'render-local-desc': 'Generate draft project files that can be imported into JianYing for local rendering.',
      'render-local-tag1': 'Reviewable',
      'render-local-tag2': 'Fine-tunable',
      'render-local-tag3': 'Suitable for local assets',
      'render-online-title': 'Online Rendering',
      'render-online-desc': 'No local environment needed, cloud rendering completed, get finished videos directly.',
      'render-online-tag1': 'Environment-free',
      'render-online-tag2': 'Fast delivery',
      'render-online-tag3': 'Suitable for batch tasks',

      // 定价
      'pricing-title': 'Clear and Transparent Credit Billing',
      'pricing-desc': 'Transparent and clear billing standards make your costs predictable',
    'pricing-rules-title': '📋 Credit Rules',
    'pricing-rules-recharge': 'Recharge Rate',
    'pricing-rules-recharge-desc': '1 RMB = 10 Credits',
    'pricing-rules-template': 'Create Template',
    'pricing-rules-template-desc': '20 credits per template (one-time)',
    'pricing-rules-generate': 'Generate Video via Make',
    'pricing-rules-generate-desc': '1 credit per second',
    'pricing-rules-render': 'Online Rendering',
    'pricing-rules-render-desc': '2 credits per second (optional)',
    'pricing-rules-gift': 'New User Gift',
    'pricing-rules-gift-desc': '120 credits upon registration',
    'pricing-examples-title': '💡 Billing Examples',
    'pricing-examples-desc': 'See actual usage scenarios and credit consumption',
    'pricing-example-a': 'Example A: 30-second video',
    'pricing-example-a-generate': 'Generate video',
    'pricing-example-a-generate-points': '30 credits',
    'pricing-example-a-render': 'Online rendering (optional)',
    'pricing-example-a-render-points': '60 credits',
    'pricing-example-a-total': 'Total',
    'pricing-example-a-total-points': '90 credits',
    'pricing-example-a-note': 'Excluding template creation',
    'pricing-example-b': 'Example B: 10 × 45-second videos',
    'pricing-example-b-generate': 'Generate videos',
    'pricing-example-b-generate-points': '450 credits',
    'pricing-example-b-render': 'Online rendering (optional)',
    'pricing-example-b-render-points': '900 credits',
    'pricing-example-b-total': 'Total',
    'pricing-example-b-total-points': '1350 credits',
    'pricing-example-b-note': 'Excluding template creation',
    'pricing-calculator-title': '🧮 Credit Calculator',
    'pricing-calculator-desc': 'Quickly calculate your project costs',
    'pricing-calculator-duration': 'Video Duration (seconds)',
    'pricing-calculator-count': 'Quantity',
    'pricing-calculator-render': 'Online Rendering (optional)',
    'pricing-calculator-points': 'Estimated Credits',
    'pricing-calculator-rmb': 'RMB Reference',
    'pricing-calculator-pay': 'Pay Now',
    
    // 应用场景
    'scenarios-title': 'Leave Repetitive Video Production to Automation',
    'scenario1-title': 'E-commerce & Brands',
    'scenario1-desc': 'Batch product card videos, promotional/holiday materials, spokesperson template automation.',
    'scenario1-tag1': 'Product Display',
    'scenario1-tag2': 'Promotions',
    'scenario2-title': 'Education & Training',
    'scenario2-desc': 'Outline-driven knowledge videos, problem explanations, terminology cards.',
    'scenario2-tag1': 'Knowledge Points',
    'scenario2-tag2': 'Problem Solving',
    'scenario3-title': 'Media & News',
    'scenario3-desc': 'Breaking news, data rankings, city/industry weekly reports.',
    'scenario3-tag1': 'Breaking News',
    'scenario3-tag2': 'Data Rankings',
    'scenario4-title': 'Corporate Training/PR',
    'scenario4-desc': 'SOP demonstrations, quarterly reports, event reviews.',
    'scenario4-tag1': 'SOP Demo',
    'scenario4-tag2': 'Quarterly Reports',
    
    // 用户评价
    'testimonials-title': 'They Are Using FreeDirector to Improve Video Production Efficiency',
    'testimonial1-name': 'Director Zhang',
    'testimonial1-company': 'E-commerce Brand',
    'testimonial1-quote': '"Batch video production went from days to hours, efficiency improved significantly."',
    'testimonial2-name': 'Manager Li',
    'testimonial2-company': 'EdTech Company',
    'testimonial2-quote': '"Templates + automation keep our video style consistent."',
    'testimonial3-name': 'Wang (Operations)',
    'testimonial3-company': 'Media Studio',
    'testimonial3-quote': '"After integrating JianYing projects, proofreading and secondary editing became very smooth."',
    'testimonial4-name': 'Supervisor Chen',
    'testimonial4-company': 'Corporate Training',
    'testimonial4-quote': '"Online rendering is perfect for batch tasks, faster delivery."',
    'testimonial5-name': 'Founder Liu',
    'testimonial5-company': 'Content Startup',
    'testimonial5-quote': '"Duration-based billing makes costs clear and controllable."',
    
    // 最终CTA
    'final-cta-title': 'Start Now, Build Your Automated Video Production Line',
    'final-cta-start': 'Get Started',
    'final-cta-examples': 'View Example Templates',
    'final-cta-guide': 'Integration Guide',
    
    // Footer
    'footer-product': 'Product',
    'footer-features': 'Features',
    'footer-pricing': 'Pricing',
    'footer-examples': 'Examples',
    'footer-resources': 'Resources',
    'footer-docs': 'Docs',
    'footer-api': 'API',
    'footer-tutorials': 'Tutorials',
    'footer-support': 'Support',
    'footer-terms': 'Terms of Service',
    'footer-privacy': 'Privacy Policy',
    'footer-customer-service': 'Customer Support',
    'footer-qr-text': 'Scan to Contact Support',
    'footer-copyright': '© Superslash / FreeDirector',
    'footer-icp': 'ICP License: 皖ICP备2024068632号-6',
    'footer-police': ' Police Record: 皖公网安备34011102003738号 '
  }
};

// 动态品牌文字颜色动画
function initDynamicBrandAnimation() {
  const brandElement = document.querySelector('.dynamic-brand');
  if (!brandElement) return;
  
  const colors = [
    '#ff0080', // 粉红色
    '#ff8000', // 橙色
    '#00ffff', // 青色
    '#8000ff', // 紫色
    '#00ff80', // 绿色
    '#ff1493', // 热粉色
    '#00bfff', // 深天蓝色
    '#ff69b4'  // 深粉色
  ];
  
  let colorIndex = 0;
  
  // 设置初始样式
  brandElement.style.fontWeight = '900';
  brandElement.style.display = 'inline-block';
  brandElement.style.transition = 'color 0.3s ease';
  brandElement.style.color = colors[0];
  
  // 启动动画
  setInterval(() => {
    colorIndex = (colorIndex + 1) % colors.length;
    brandElement.style.color = colors[colorIndex];
  }, 250); // 每250毫秒切换一次颜色，2秒完成一个循环
}

// 页面加载完成后启动动画
document.addEventListener('DOMContentLoaded', initDynamicBrandAnimation);

// 平滑滚动到锚点
document.querySelectorAll('a[href^="#"]').forEach(a=>{
  a.addEventListener('click',e=>{
    const id=a.getAttribute('href').slice(1);
    const el=document.getElementById(id);
    if(el){
      e.preventDefault();
      el.scrollIntoView({behavior:'smooth',block:'start'});
    }
  })
});

// 计费试算器
const durationEl=document.getElementById('duration');
const countEl=document.getElementById('count');
const renderOnlineEl=document.getElementById('renderOnline');
const pointsEl=document.getElementById('points');
const rmbEl=document.getElementById('rmb');

function updateCalc(){
  const d=Math.max(0,parseInt(durationEl.value||0,10));
  const c=Math.max(1,parseInt(countEl.value||1,10));
  const chunk=Math.floor(d/10); // 不足10秒不消耗
  const gen=chunk*c;
  const online=renderOnlineEl.checked?chunk*c:0;
  const total=gen+online;
  pointsEl.textContent=String(total);
  rmbEl.textContent=(total/10).toFixed(2);
}

for(const el of [durationEl,countEl,renderOnlineEl]){
  el && el.addEventListener('input',updateCalc);
}
updateCalc();

// 滚动进场：IntersectionObserver
const observer=new IntersectionObserver((entries)=>{
  entries.forEach(entry=>{
    if(entry.isIntersecting){
      entry.target.classList.add('in-view');
      observer.unobserve(entry.target);
    }
  });
},{threshold:0.1});

document.querySelectorAll('.reveal').forEach(el=>observer.observe(el));

// 典型场景轮播画廊控制器
class CarouselGallery {
  constructor() {
    this.currentIndex = 0;
    this.cards = [];
    this.indicators = [];
    this.carouselContainer = null;
    this.autoPlayInterval = null;
    this.autoPlayDelay = 4000; // 4秒自动切换
    this.isTransitioning = false;
    this.isMobile = window.innerWidth <= 480;
    this.isTablet = window.innerWidth <= 768 && window.innerWidth > 480;
    
    this.init();
  }

  init() {
    // 等待DOM加载完成
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => this.setup());
    } else {
      this.setup();
    }
  }

  setup() {
    // 获取轮播元素
    this.carouselContainer = document.querySelector('.carousel-container');
    this.cards = Array.from(document.querySelectorAll('.carousel-card'));
    this.indicators = Array.from(document.querySelectorAll('.indicator'));

    if (!this.carouselContainer || this.cards.length === 0) {
      console.warn('轮播画廊元素未找到');
      return;
    }

    // 初始化卡片位置
    this.updateCardPositions();
    
    // 绑定事件
    this.bindEvents();
    
    // 开始自动播放
    this.startAutoPlay();
    
    // 添加鼠标悬停暂停功能
    this.setupHoverPause();
  }

  updateCardPositions() {
    this.cards.forEach((card, index) => {
      // 移除所有状态类
      card.classList.remove('active');
      
      // 计算相对于当前索引的位置
      let position = index - this.currentIndex;
      
      // 处理循环位置 - 支持左右两侧隐藏
      if (position < -1) {
        position += this.cards.length;
      } else if (position > 2) {
        position -= this.cards.length;
      }
      
      // 设置data-index属性来控制CSS样式
      card.setAttribute('data-index', position);
      
      // 为当前卡片添加active类
      if (index === this.currentIndex) {
        card.classList.add('active');
      }
    });

    // 更新指示器
    this.updateIndicators();
  }

  updateIndicators() {
    this.indicators.forEach((indicator, index) => {
      indicator.classList.toggle('active', index === this.currentIndex);
    });
  }

  nextSlide() {
    if (this.isTransitioning) return;
    
    this.isTransitioning = true;
    this.currentIndex = (this.currentIndex + 1) % this.cards.length;
    this.updateCardPositions();
    
    // 防止过快切换
    setTimeout(() => {
      this.isTransitioning = false;
    }, 800);
  }

  prevSlide() {
    if (this.isTransitioning) return;
    
    this.isTransitioning = true;
    this.currentIndex = this.currentIndex === 0 ? this.cards.length - 1 : this.currentIndex - 1;
    this.updateCardPositions();
    
    setTimeout(() => {
      this.isTransitioning = false;
    }, 800);
  }

  goToSlide(index) {
    if (this.isTransitioning || index === this.currentIndex) return;
    
    this.isTransitioning = true;
    this.currentIndex = index;
    this.updateCardPositions();
    
    setTimeout(() => {
      this.isTransitioning = false;
    }, 800);
  }

  startAutoPlay() {
    // 启动自动移动动画，每3秒移动一次
    this.autoPlayInterval = setInterval(() => {
      this.nextSlide();
    }, 3000); // 每3000毫秒（3秒）移动一次
    console.log('卡片自动移动动画已启动');
  }

  stopAutoPlay() {
    // 停止自动移动动画
    if (this.autoPlayInterval) {
      clearInterval(this.autoPlayInterval);
      this.autoPlayInterval = null;
    }
    console.log('卡片自动移动动画已停止');
  }setupHoverPause() {
    // hover事件已移除，无响应
  }

  bindEvents() {
    // 指示器点击事件
    this.indicators.forEach((indicator, index) => {
      indicator.addEventListener('click', () => {
        this.goToSlide(index);
        this.startAutoPlay(); // 重新开始自动播放
      });
    });

    // 卡片点击事件
    this.cards.forEach((card, index) => {
      card.addEventListener('click', () => {
        if (index !== this.currentIndex) {
          this.goToSlide(index);
          this.startAutoPlay();
        }
      });
    });

    // 键盘导航（仅桌面端）
    if (!this.isMobile) {
      document.addEventListener('keydown', (e) => {
        if (!this.carouselContainer) return;
        
        switch(e.key) {
          case 'ArrowLeft':
            e.preventDefault();
            this.prevSlide();
            this.startAutoPlay();
            break;
          case 'ArrowRight':
            e.preventDefault();
            this.nextSlide();
            this.startAutoPlay();
            break;
        }
      });
    }

    // 触摸滑动支持（移动端）
    this.setupTouchEvents();
    
    // 窗口大小变化监听
    this.setupResizeHandler();
  }

  setupTouchEvents() {
    let startX = 0;
    let startY = 0;
    let endX = 0;
    let endY = 0;
    let startTime = 0;

    this.carouselContainer.addEventListener('touchstart', (e) => {
      startX = e.touches[0].clientX;
      startY = e.touches[0].clientY;
      startTime = Date.now();
      this.stopAutoPlay(); // 触摸时暂停自动播放
    }, { passive: true });

    this.carouselContainer.addEventListener('touchend', (e) => {
      endX = e.changedTouches[0].clientX;
      endY = e.changedTouches[0].clientY;
      
      const deltaX = endX - startX;
      const deltaY = endY - startY;
      const deltaTime = Date.now() - startTime;
      
      // 移动端优化：更敏感的滑动检测
      const minDistance = this.isMobile ? 30 : 50;
      const maxTime = 300; // 最大滑动时间
      
      // 确保是水平滑动且滑动距离足够，时间不超过限制
      if (Math.abs(deltaX) > Math.abs(deltaY) && 
          Math.abs(deltaX) > minDistance && 
          deltaTime < maxTime) {
        if (deltaX > 0) {
          this.prevSlide(); // 向右滑动，逆向滚动
        } else {
          this.nextSlide(); // 向左滑动，顺向滚动（从右往左）
        }
      }
      
      // 延迟重启自动播放，给用户更好的控制感
      setTimeout(() => {
        this.startAutoPlay();
      }, 1000);
    }, { passive: true });
  }

  setupResizeHandler() {
    let resizeTimeout;
    
    window.addEventListener('resize', () => {
      clearTimeout(resizeTimeout);
      resizeTimeout = setTimeout(() => {
        const newIsMobile = window.innerWidth <= 480;
        const newIsTablet = window.innerWidth <= 768 && window.innerWidth > 480;
        
        // 如果设备类型发生变化，重新初始化
        if (newIsMobile !== this.isMobile || newIsTablet !== this.isTablet) {
          this.isMobile = newIsMobile;
          this.isTablet = newIsTablet;
          this.updateCardPositions();
        }
      }, 250);
    });
  }

  // 公共方法：暂停/恢复自动播放
  pause() {
    this.stopAutoPlay();
  }

  resume() {
    this.startAutoPlay();
  }

  // 公共方法：销毁轮播
  destroy() {
    this.stopAutoPlay();
    // 移除事件监听器等清理工作
    this.cards = [];
    this.indicators = [];
    this.carouselContainer = null;
  }
}

// 初始化轮播画廊
document.addEventListener('DOMContentLoaded', () => {
  window.carouselGallery = new CarouselGallery();
  console.log('🎬 轮播画廊已初始化');
});

// 页面可见性API - 当页面不可见时暂停轮播
document.addEventListener('visibilitychange', () => {
  if (window.carouselGallery) {
    if (document.hidden) {
      window.carouselGallery.pause();
    } else {
      window.carouselGallery.resume();
    }
  }
});

// 图片鼠标跟随倾斜效果
class ImageTiltEffect {
  constructor() {
    this.init();
  }

  init() {
    // 选择所有需要倾斜效果的图片
    const images = document.querySelectorAll('.accent, .workflow-image, .feature-icon');
    
    images.forEach(img => {
      this.setupTiltEffect(img);
    });
  }

  setupTiltEffect(element) {
    element.addEventListener('mouseenter', (e) => {
      this.handleMouseEnter(e);
    });

    element.addEventListener('mousemove', (e) => {
      this.handleMouseMove(e);
    });

    element.addEventListener('mouseleave', (e) => {
      this.handleMouseLeave(e);
    });
  }

  handleMouseEnter(e) {
    const element = e.currentTarget;
    element.style.transition = 'transform 0.1s ease-out';
  }

  handleMouseMove(e) {
    const element = e.currentTarget;
    const rect = element.getBoundingClientRect();
    
    // 计算鼠标相对于元素中心的位置
    const centerX = rect.left + rect.width / 2;
    const centerY = rect.top + rect.height / 2;
    
    const mouseX = e.clientX - centerX;
    const mouseY = e.clientY - centerY;
    
    // 计算倾斜角度 (限制在-15到15度之间)
    const maxTilt = 15;
    const tiltX = (mouseY / (rect.height / 2)) * maxTilt;
    const tiltY = (mouseX / (rect.width / 2)) * maxTilt;
    
    // 应用3D变换
    element.style.transform = `
      perspective(1000px) 
      rotateX(${-tiltX}deg) 
      rotateY(${tiltY}deg) 
      scale3d(1.05, 1.05, 1.05)
    `;
  }

  handleMouseLeave(e) {
    const element = e.currentTarget;
    element.style.transition = 'transform 0.3s ease-out';
    element.style.transform = 'perspective(1000px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)';
  }
}

// 初始化图片倾斜效果
document.addEventListener('DOMContentLoaded', () => {
  window.imageTiltEffect = new ImageTiltEffect();
  console.log('🎨 图片倾斜效果已初始化');
});

// 用户背书卡片随机放大动画
class TestimonialHighlighter {
  constructor() {
    this.testimonialItems = [];
    this.currentHighlighted = -1;
    this.intervalId = null;
    this.isVisible = false;
    this.init();
  }

  init() {
    // 获取所有用户背书卡片
    this.testimonialItems = document.querySelectorAll('.testimonial-item');
    
    if (this.testimonialItems.length === 0) return;

    // 设置Intersection Observer来检测区块是否可见
    this.setupVisibilityObserver();
    
    // 开始动画
    this.startAnimation();
  }

  setupVisibilityObserver() {
    const testimonialsSection = document.getElementById('testimonials');
    if (!testimonialsSection) return;

    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          this.isVisible = true;
          this.startAnimation();
        } else {
          this.isVisible = false;
          this.stopAnimation();
        }
      });
    }, {
      threshold: 0.3 // 当30%的区域可见时触发
    });

    observer.observe(testimonialsSection);
  }

  startAnimation() {
    if (!this.isVisible || this.intervalId) return;

    // 立即高亮第一个卡片
    this.highlightRandomCard();

    // 每3秒切换一次
    this.intervalId = setInterval(() => {
      this.highlightRandomCard();
    }, 3000);
  }

  stopAnimation() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
      this.intervalId = null;
    }
    
    // 清除所有高亮状态
    this.clearAllHighlights();
  }

  highlightRandomCard() {
    if (this.testimonialItems.length === 0) return;

    // 清除当前高亮
    this.clearAllHighlights();

    // 生成新的随机索引，确保不与当前相同
    let newIndex;
    do {
      newIndex = Math.floor(Math.random() * this.testimonialItems.length);
    } while (newIndex === this.currentHighlighted && this.testimonialItems.length > 1);

    // 高亮新卡片
    this.testimonialItems[newIndex].classList.add('highlighted');
    this.currentHighlighted = newIndex;
  }

  clearAllHighlights() {
    this.testimonialItems.forEach(item => {
      item.classList.remove('highlighted');
    });
  }

  destroy() {
    this.stopAnimation();
    this.clearAllHighlights();
  }
}

// 页面加载完成后启动用户背书卡片动画
document.addEventListener('DOMContentLoaded', () => {
  new TestimonialHighlighter();
});

// 页面可见性变化时控制动画
document.addEventListener('visibilitychange', () => {
  const highlighter = window.testimonialHighlighter;
  if (highlighter) {
    if (document.hidden) {
      highlighter.stopAnimation();
    } else {
      highlighter.startAnimation();
    }
  }
});

// 弹窗功能
class ModalManager {
  constructor() {
    this.init();
  }

  init() {
    // 绑定触发器点击事件
    document.addEventListener('click', (e) => {
      if (e.target.classList.contains('modal-trigger')) {
        e.preventDefault();
        const modalId = e.target.getAttribute('data-modal');
        this.openModal(modalId);
      }
    });

    // 绑定关闭按钮事件
    document.addEventListener('click', (e) => {
      if (e.target.classList.contains('modal-close')) {
        this.closeModal(e.target.closest('.modal'));
      }
    });

    // 点击背景关闭弹窗
    document.addEventListener('click', (e) => {
      if (e.target.classList.contains('modal')) {
        this.closeModal(e.target);
      }
    });

    // ESC键关闭弹窗
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') {
        const openModal = document.querySelector('.modal.show');
        if (openModal) {
          this.closeModal(openModal);
        }
      }
    });
  }

  openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
      modal.classList.add('show');
      document.body.style.overflow = 'hidden'; // 防止背景滚动
      
      // 聚焦到弹窗内容，提高可访问性
      const modalContent = modal.querySelector('.modal-content');
      if (modalContent) {
        modalContent.focus();
      }
    }
  }

  closeModal(modal) {
    if (modal) {
      modal.classList.remove('show');
      document.body.style.overflow = ''; // 恢复背景滚动
    }
  }

  closeAllModals() {
    const openModals = document.querySelectorAll('.modal.show');
    openModals.forEach(modal => this.closeModal(modal));
  }
}

// 初始化弹窗管理器
document.addEventListener('DOMContentLoaded', () => {
  new ModalManager();
});

// 语言切换管理器
class LanguageManager {
  constructor() {
    this.currentLang = 'zh'; // 默认中文
    this.init();
  }

  init() {
    // 绑定语言切换按钮事件
    const langSwitch = document.getElementById('langSwitch');
    if (langSwitch) {
      langSwitch.addEventListener('click', () => {
        this.toggleLanguage();
      });
    }

    // 初始化页面语言
    this.updatePageLanguage();
  }

  toggleLanguage() {
    this.currentLang = this.currentLang === 'zh' ? 'en' : 'zh';
    this.updatePageLanguage();
    this.updateSwitchButton();
  }

  updatePageLanguage() {
    const elements = document.querySelectorAll('[data-lang-key]');
    elements.forEach(element => {
      const key = element.getAttribute('data-lang-key');
      if (languageData[this.currentLang] && languageData[this.currentLang][key]) {
        // 检查是否包含HTML标签
        const text = languageData[this.currentLang][key];
        if (text.includes('<strong>') || text.includes('<')) {
          element.innerHTML = text;
        } else {
          element.textContent = text;
        }
      }
    });

    // 特殊处理Hero标题中的动态品牌文字
    if (this.currentLang === 'en') {
      const heroTitle = document.querySelector('[data-lang-key="hero-title"]');
      if (heroTitle) {
        heroTitle.innerHTML = 'Batch Generate High-Quality Videos with "<span class="dynamic-brand" id="brand-text">Make+JianYing</span>"';
      }
    } else {
      const heroTitle = document.querySelector('[data-lang-key="hero-title"]');
      if (heroTitle) {
        heroTitle.innerHTML = '用"<span class="dynamic-brand" id="brand-text">Make+剪映</span>"，批量生成高质量视频';
      }
    }
  }

  updateSwitchButton() {
    const langFlag = document.querySelector('.lang-flag');
    const langText = document.querySelector('.lang-text');
    
    if (langFlag && langText) {
      if (this.currentLang === 'zh') {
        langFlag.textContent = '🇬🇧';
        langText.textContent = 'EN';
      } else {
        langFlag.textContent = '🇨🇳';
        langText.textContent = '中';
      }
    }
  }
}

// 初始化语言管理器
document.addEventListener('DOMContentLoaded', () => {
  new LanguageManager();
});
